/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import dao.Dao;
import entidades.Artista;
import entidades.Musica;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.eclipse.persistence.sessions.Session;

/**
 *
 * @author a968730
 */
@WebServlet(name = "ServletArtista", urlPatterns = {"/ServletArtista"})
public class ServletArtista extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ServletArtista</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ServletArtista at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String op = (String) request.getParameter("op");
        int id = Integer.parseInt((String) request.getParameter("id"));
        HttpSession session = request.getSession(true);
        Dao<Artista> dao = new Dao<Artista>(Artista.class);
        Dao<Musica> dao2 = new Dao<Musica>(Musica.class);
        if (op.equals("remover")) {
            // Dao<Artista> dao = new Dao<Artista>(Artista.class);
            dao.remove(id);

            //String nome = (String) session.getAttribute("nome");
            session.setAttribute("arrayArtista", dao.listByNome(""));

            response.sendRedirect("gerenciarArtista.jsp");

        } else if (op.equals("listMusic")) {


            int idArtista = Integer.parseInt(request.getParameter("id"));


            Artista art = dao.get(idArtista);
            List<Musica> musicas = art.getMusicas();

            session.setAttribute("musicas", musicas);
            session.setAttribute("musicas2", musicas);
            session.setAttribute("Artista", art);
            response.sendRedirect("gerenciarMusica.jsp");


        } else if (op.equals("removerMusica")) {
            Artista art = (Artista) session.getAttribute("Artista");
            List<Musica> m = art.getMusicas();
            Musica m1 = null;
            for (int i = 0; i < m.size(); i++) {
                if (m.get(i).getId() == id) {
                    m1 = m.get(i);
                    m.remove(m.get(i));
                }
            }
            session.setAttribute("musicas", m);
            art.getMusicas().remove(m1);
            m1.getArtistas().remove(art);
            dao2.update(m1);
            dao.update(art);
            response.sendRedirect("gerenciarMusica.jsp");
        }

    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
     public final String dir = "/files/";
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         Upload upload = new Upload(getServletContext().getRealPath(dir));
         // Retorna um list com todos os componentes de uma requisição
             List list1 = upload.processRequest(request);

        // Neste Map você obteve todos os campos do formulário.
             Map<String, String> map = upload.getFormValues(list1);
             //String foto = Global.getNomeFoto();
        String nome = map.get("nome");
        String op = map.get("op");
        String nomeBuscar = map.get("buscar");
        HttpSession session = request.getSession(true);

        Artista p = new Artista();
        p.setNome(nome);

        Dao<Artista> dao = new Dao<Artista>(Artista.class);
        Dao<Musica> dao2 = new Dao<Musica>(Musica.class);
        boolean achou = false;
        if (op.equals("cadastrar")) {
             

       
             
            String[] valores = request.getParameterValues("musicas");
           String foto= map.get("foto");
           p.setCaminhoFoto(foto);

            ArrayList<Integer> array2 = new ArrayList();
            for (int i = 0; valores.length > i;) {
                array2.add(Integer.parseInt(valores[i]));
                i++;
            }
            ArrayList<Musica> ms = new ArrayList<Musica>();
            for (int i = 0; array2.size() > i;) {
                ms.add(dao2.get(array2.get(i)));
                i++;
            }
            p.setMusicas(ms);
            


            dao.insert(p);
            List<Artista> array;
            array = dao.listByNome("");
            session.setAttribute("arrayArtista", array);
            RequestDispatcher rd = request.getRequestDispatcher("gerenciarArtista.jsp");
            rd.forward(request, response);


        } else if (op.equals("pesquisar")) {
            List<Artista> array;
            array = dao.listByNome(nomeBuscar);
            session.setAttribute("nome", nomeBuscar);
            session.setAttribute("arrayArtista", array);
            RequestDispatcher rd = request.getRequestDispatcher("gerenciarArtista.jsp");
            rd.forward(request, response);

        } else if (op.equals("update")) {
            Artista art = (Artista) session.getAttribute("Artista");
            art.setNome(nome);
            dao.update(art);
        }

    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
